//
//  LZMoreViewController.m
//  沙哈拉FM
//
//  Created by dllo on 15/11/9.
//  Copyright © 2015年 S1mpl3. All rights reserved.
//

#import "LZMoreViewController.h"
#import "TabBarController.h"
#import "FitHeader.h"
#import "LZHotOrNewTableViewCell.h"
#import "TwoToOne.h"
#import "TheHost.h"
#import "TitleHeadView.h"
#import "BaseView.h"
#import "TheHostLastCollectionViewCell.h"
#import "S1mpl3HeadInfoViewController.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "Model.h"
#import "UIImage+GIF.h"


@interface LZMoreViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong)UISegmentedControl *segment;
@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NSMutableArray *dataArray;//在本页传值
@property(nonatomic, strong)NSMutableArray *category_listArray;
@property(nonatomic, strong)TheHost *host;
@property(nonatomic, strong)NSString *string;
@property(nonatomic, strong)NSString *urlString;
@property(nonatomic, strong)TitleHeadView *titleHeadView;
@property(nonatomic, strong)BaseView *backView;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, assign)NSInteger selectColorFlag;

@property(nonatomic, strong)NSMutableArray *array;

@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, assign)NSInteger page;

@end

@implementation LZMoreViewController

- (void)viewWillAppear:(BOOL)animated{
    [[TabBarController shareInstance] remainButtonOfPlay:YES];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[Model shareInstance].TitleColor, NSForegroundColorAttributeName, nil]];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [[TabBarController shareInstance] remainButtonOfPlay:NO];
    [_titleHeadView removeFromSuperview];
    _titleHeadView = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _array = [NSMutableArray array];
    _category_listArray = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    
    _flag = 0;
    _selectColorFlag = 0;
    _titleHeadView = [[TitleHeadView alloc]initWithFrame:CGRectMake(0, 0, 120 * FITWidth, 20 * FITHeight)];
    if ([_zhuBoString isEqualToString:@"新晋主播"]) {
        _titleHeadView.titleLabel.text = _zhuBoString;
    }else{
        
        _titleHeadView.titleLabel.text = [NSString stringWithFormat:@"%@   ∨", _zhuBoString];
    }
    _titleHeadView.titleImageView.image = [UIImage imageNamed:@"下箭头灰色"];
    self.navigationItem.titleView = _titleHeadView.titleLabel;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleHeadAction)];
    _titleHeadView.titleLabel.userInteractionEnabled = YES;
    [_titleHeadView.titleLabel addGestureRecognizer:tap];

    self.view.backgroundColor = [UIColor whiteColor];
    
 
    _segment = [[UISegmentedControl alloc]initWithItems:@[@"最热", @"最新"]];
    _segment.frame = CGRectMake(20 * FITWidth, 5 * FITHeight, self.view.frame.size.width - 40 * FITWidth, 30 * FITHeight);
    _segment.tintColor = [UIColor redColor];
    [_segment addTarget:self action:@selector(segmentOneAction:) forControlEvents:UIControlEventValueChanged];
    [_segment setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil] forState:UIControlStateNormal];
    [self.view addSubview:_segment];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40 * FITHeight, self.view.frame.size.width, self.view.frame.size.height - 64 - 40 * FITHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    [[[_progressView subviews]firstObject] removeFromSuperview];
    [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
    [_progressView setMode:0];
    [_progressView show:YES];
    NSString  *name = @"RED.gif";
    _progressView.color = [UIColor clearColor];
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 10;
    imageView.opaque = NO;
    
    [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
    
    imageView.image = [UIImage sd_animatedGIFWithData:imageData];
    [[[_progressView subviews] lastObject] addSubview:imageView];    [self.view addSubview:_progressView];
    
    _segment.selectedSegmentIndex = 0;
    
    _page = 1;
    [self getData];
    //下拉刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataArray removeAllObjects];
        _page = 1;
        [self getData];
    }];
    //上拉加载
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getData];
    }];
    
    _backView = [[BaseView alloc]initWithFrame:CGRectMake(0, -330 * FITHeight, self.view.frame.size.width, 330 * FITHeight)];
    _backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(375 * FITWidth / 4, 40 * FITHeight);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 5, 0);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = 0;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, _backView.frame.size.height) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    _collectionView.backgroundColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1];
    [_collectionView registerClass:[TheHostLastCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [_backView addSubview:_collectionView];
    
    
}
#pragma mark - item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _category_listArray.count;
}
#pragma mark - cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TheHostLastCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor grayColor];
    if (indexPath.row == _selectColorFlag) {
        
        cell.titleLabel.textColor = [UIColor redColor];
    }
    
    cell.host = _category_listArray[indexPath.row];
    return cell;
}
#pragma mark - cell点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    _array = [NSMutableArray array];
    
    _nameString = [_category_listArray[indexPath.row] name];
 
    _selectColorFlag = indexPath.row;
    _titleHeadView.titleLabel.text = [NSString stringWithFormat:@"%@   ∨",[_category_listArray[indexPath.row] title]];
    
    
    [_tableView.mj_header beginRefreshing];
    
    [self getData];
    [UIView animateWithDuration:.4 animations:^{
        CGPoint point = _backView.center;
        point.y -= 330 * FITHeight;
        [_backView setCenter:point];
        _flag = 0;
    }];
}
#pragma mark - title的点击事件
- (void)titleHeadAction{
    if (_flag == 0) {
        
        [UIView animateWithDuration:.8 animations:^{
        CGPoint point = _backView.center;
        point.y += 330 * FITHeight;
        [_backView setCenter:point];
        }];
        _flag = 1;
        
    }else{
        [UIView animateWithDuration:.8 animations:^{
            CGPoint point = _backView.center;
            point.y -= 330 * FITHeight;
            [_backView setCenter:point];
        }];
        _flag = 0;
    }
}
- (void)getData{
    
    _category_listArray = [NSMutableArray array];
    NSString *urlBigString = @"http://mobile.ximalaya.com/m/category_tag_menu?device=android&type=user";
    [TwoToOne getDataByString:urlBigString BodyString:nil WithDataBlock:^(id data) {
        NSDictionary *dataDic = [data objectForKey:@"data"];
        NSArray *category_listArray = [dataDic objectForKey:@"category_list"];
        
        for (NSDictionary *dic in category_listArray) {
            _host = [[TheHost alloc]init];
            [_host setValuesForKeysWithDictionary:dic];
            [_category_listArray addObject:_host];
        }
        [_tableView reloadData];
        [_collectionView reloadData];
    }];
    
    if (_segment.selectedSegmentIndex == 0) {
        _string = @"hot";
    }else{
        _string = @"new";
    }
    
    if ([_zhuBoString isEqualToString:@"新晋主播"]) {
        _segment.hidden = YES;
        _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 49);
        _urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_list?category_name=all&condition=new&device=android&page=%ld&per_page=20", _page];
    }else{
        
        _urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_list?category_name=%@&condition=%@&device=android&page=%ld&per_page=20", _nameString, _string, _page];
    }
    
    [TwoToOne getDataByString:_urlString BodyString:nil WithDataBlock:^(id data) {
        
//        NSLog(@"%@", _urlString);
        
        if ([[data objectForKey:@"list"]count] == 0) {
            [_tableView.mj_footer endRefreshing];
            _tableView.mj_footer.state = MJRefreshStateNoMoreData;
            return ;
        }
        
        NSArray *listArray = [data objectForKey:@"list"];
        [_array addObjectsFromArray:listArray];
        for (NSDictionary *dic in listArray) {
            TheHostList *hostList = [[TheHostList alloc]init];
            [hostList setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:hostList];
        }
        [_tableView reloadData];
        [_collectionView reloadData];
        [_progressView removeFromSuperview];
        //停止刷新
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header endRefreshing];
    }];
}
- (void)segmentOneAction:(UISegmentedControl *)seg{
    
    if (seg.selectedSegmentIndex == 0) {
        _array = [NSMutableArray array];
        [self getData];
        [_tableView.mj_header beginRefreshing];
    }else{
        _array = [NSMutableArray array];
        [self getData];
        [_tableView.mj_header beginRefreshing];
    }
    
}
#pragma mark - cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
#pragma mark - cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    LZHotOrNewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[LZHotOrNewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = 0;
    cell.hostList = _dataArray[indexPath.row];
    return cell;
}
#pragma mark - cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130 * FITHeight;
}
#pragma mark - tableView点击跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    S1mpl3HeadInfoViewController *s1mpl3Head = [[S1mpl3HeadInfoViewController alloc]init];
    s1mpl3Head.s1mpl3HeadDataSourceDic = _array[indexPath.row];
    [self.navigationController pushViewController:s1mpl3Head animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
